<?php

namespace app\controller\crm;

use app\BaseController;
use think\facade\Db;
use think\facade\Request;
use think\facade\Validate;

/**
 * 财务审核管理
 */
class Finance extends BaseController
{
    /**
     * 获取待审核订单列表
     */
    public function pendingList()
    {
        $params = Request::param();
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 20;
        $customerName = $params['customer_name'] ?? '';

        $query = Db::name('crm_order')
            ->alias('o')
            ->field('o.id, o.order_no, o.customer_name, o.total_amount, o.paid_amount, o.approval_status, o.create_time, c.name as customer_name_full')
            ->leftJoin('crm_customer c', 'o.customer_id = c.id')
            ->where('o.delete_time', 0)
            ->where('o.approval_status', 'in', [0, 1])  // 待审核或审核中
            ->where('o.total_amount', '>', 0);  // 免费订单不需要财务审核

        if ($customerName) {
            $query->where('o.customer_name', 'like', '%' . $customerName . '%');
        }

        $total = $query->count();
        $list = $query->order('o.create_time', 'desc')
            ->page($page, $limit)
            ->select();

        return $this->paginate($list ? $list->toArray() : [], $total, (int)$page, (int)$limit);
    }

    /**
     * 添加到账记录
     */
    public function addRecord()
    {
        $params = Request::param();

        // 参数验证
        $validate = Validate::rule([
            'order_id|订单ID' => 'require|number',
            'payment_type|支付类型' => 'require|in:1,2',
            'received_amount|收款金额' => 'require|gt:0',
            'received_date|收款日期' => 'require',
            'payment_method|支付方式' => 'require|in:1,2,3,4,5',
            'payer_name|付款人姓名' => 'require'
        ]);

        if (!$validate->check($params)) {
            return $this->error($validate->getError());
        }

        // 检查订单是否存在
        $order = Db::name('crm_order')->where('id', $params['order_id'])->find();
        if (!$order) {
            return $this->error('订单不存在');
        }

        $data = [
            'order_id' => $params['order_id'],
            'payment_type' => $params['payment_type'],
            'received_amount' => $params['received_amount'],
            'received_date' => strtotime($params['received_date']),
            'payment_method' => $params['payment_method'],
            'payment_proof_files' => isset($params['payment_proof_files']) ? json_encode($params['payment_proof_files']) : '',
            'payer_name' => $params['payer_name'],
            'verification_status' => 0,  // 未核实
            'remark' => $params['remark'] ?? '',
            'create_time' => time(),
            'update_time' => time()
        ];

        $id = Db::name('crm_finance_record')->insertGetId($data);

        if ($id) {
            // 更新订单的已支付金额
            $this->updateOrderPaidAmount($params['order_id']);

            return $this->success(['id' => $id], '添加成功');
        }

        return $this->error('添加失败');
    }

    /**
     * 获取订单到账记录
     */
    public function records()
    {
        $orderId = Request::param('order_id');
        if (!$orderId) {
            return $this->error('参数错误');
        }

        $records = Db::name('crm_finance_record')
            ->alias('fr')
            ->field('fr.*, u.name as verifier_name')
            ->leftJoin('admin u', 'fr.verifier_id = u.id')
            ->where('fr.order_id', $orderId)
            ->order('fr.create_time', 'desc')
            ->select();

        return $this->success($records ? $records->toArray() : []);
    }

    /**
     * 财务审核通过
     */
    public function verify()
    {
        $orderId = Request::param('order_id');
        if (!$orderId) {
            return $this->error('参数错误');
        }

        $userId = $this->getUserId();
        if (!$userId) {
            return $this->error('未登录或登录已过期', 401);
        }

        // 检查订单是否存在
        $order = Db::name('crm_order')->where('id', $orderId)->find();
        if (!$order) {
            return $this->error('订单不存在');
        }

        // 检查是否已有财务审核记录
        $hasFinanceRecord = Db::name('crm_finance_record')
            ->where('order_id', $orderId)
            ->where('verification_status', 1)
            ->count();

        if ($hasFinanceRecord == 0) {
            return $this->error('没有核实通过的财务记录');
        }

        // 更新所有财务记录为已核实
        Db::name('crm_finance_record')
            ->where('order_id', $orderId)
            ->where('verification_status', 0)
            ->update([
                'verification_status' => 1,
                'verifier_id' => $userId,
                'verification_time' => time(),
                'update_time' => time()
            ]);

        // 检查合同审核状态
        $contractVerified = Db::name('crm_contract_archive')
            ->where('order_id', $orderId)
            ->where('archive_status', 1)
            ->count() > 0;

        // 如果合同审核也通过，则生成工单
        if ($contractVerified) {
            $this->generateWorkOrder($orderId);
        }

        return $this->success([], '财务审核通过');
    }

    /**
     * 核实单笔到账记录
     */
    public function verifyRecord()
    {
        $recordId = Request::param('record_id');
        if (!$recordId) {
            return $this->error('参数错误');
        }

        $userId = $this->getUserId();
        if (!$userId) {
            return $this->error('未登录或登录已过期', 401);
        }

        $result = Db::name('crm_finance_record')->where('id', $recordId)->update([
            'verification_status' => 1,
            'verifier_id' => $userId,
            'verification_time' => time(),
            'update_time' => time()
        ]);

        if ($result !== false) {
            // 更新订单的已支付金额
            $record = Db::name('crm_finance_record')->find($recordId);
            $this->updateOrderPaidAmount($record['order_id']);

            return $this->success([], '核实成功');
        }

        return $this->error('核实失败');
    }

    /**
     * 删除到账记录
     */
    public function deleteRecord()
    {
        $recordId = Request::param('record_id');
        if (!$recordId) {
            return $this->error('参数错误');
        }

        // 检查记录是否存在
        $record = Db::name('crm_finance_record')->find($recordId);
        if (!$record) {
            return $this->error('记录不存在');
        }

        // 检查记录是否已核实
        if ($record['verification_status'] == 1) {
            return $this->error('已核实的记录不能删除');
        }

        $result = Db::name('crm_finance_record')->where('id', $recordId)->delete();

        if ($result !== false) {
            // 更新订单的已支付金额
            $this->updateOrderPaidAmount($record['order_id']);

            return $this->success([], '删除成功');
        }

        return $this->error('删除失败');
    }

    /**
     * 获取财务审核统计
     */
    public function stats()
    {
        // 待审核订单数
        $pendingOrders = Db::name('crm_order')
            ->where('approval_status', 'in', [0, 1])
            ->where('total_amount', '>', 0)
            ->count();

        // 待核实记录数
        $pendingRecords = Db::name('crm_finance_record')
            ->where('verification_status', 0)
            ->count();

        // 本月到账金额
        $startOfMonth = strtotime(date('Y-m-01'));
        $thisMonthAmount = Db::name('crm_finance_record')
            ->where('verification_status', 1)
            ->where('create_time', '>=', $startOfMonth)
            ->sum('received_amount');

        return $this->success([
            'pending_orders' => $pendingOrders,
            'pending_records' => $pendingRecords,
            'this_month_amount' => $thisMonthAmount
        ]);
    }

    /**
     * 更新订单的已支付金额
     */
    private function updateOrderPaidAmount($orderId)
    {
        $totalPaid = Db::name('crm_finance_record')
            ->where('order_id', $orderId)
            ->where('verification_status', 1)
            ->sum('received_amount');

        Db::name('crm_order')->where('id', $orderId)->update([
            'paid_amount' => $totalPaid,
            'update_time' => time()
        ]);
    }

    /**
     * 生成工单
     */
    private function generateWorkOrder($orderId)
    {
        $order = Db::name('crm_order')->find($orderId);
        if (!$order) {
            return false;
        }

        // 生成工单编号
        $workOrderNo = $this->generateWorkOrderNo();

        // 根据订单类型确定工单类别
        $category = 1;  // 默认案件委托工单
        if (in_array($order['order_sub_type'], [2, 3])) {
            $category = 2;  // 法务工单
        }

        $workOrderData = [
            'order_id' => $orderId,
            'work_order_no' => $workOrderNo,
            'category' => $category,
            'title' => '订单[' . $order['order_no'] . ']处理工单',
            'description' => '订单总金额：' . $order['total_amount'] . '元，已支付金额：' . $order['paid_amount'] . '元',
            'status' => 1,  // 待分配
            'priority' => 2,  // 中等
            'customer_id' => $order['customer_id'],
            'customer_name' => $order['customer_name'],
            'create_time' => time(),
            'update_time' => time()
        ];

        $workOrderId = Db::name('work_order')->insertGetId($workOrderData);

        if ($workOrderId) {
            // 记录工单创建进度
            Db::name('work_order_progress')->insert([
                'work_order_id' => $workOrderId,
                'operator_id' => 0,  // 系统操作
                'operator_name' => '系统',
                'progress_type' => 1,
                'new_status' => 1,
                'content' => '订单审核通过，工单已创建',
                'create_time' => time()
            ]);

            // 更新订单状态
            Db::name('crm_order')->where('id', $orderId)->update([
                'delivery_status' => 1,  // 交付中
                'update_time' => time()
            ]);
        }

        return $workOrderId;
    }

    /**
     * 生成工单编号
     */
    private function generateWorkOrderNo()
    {
        $prefix = 'WO';
        $date = date('Ymd');
        $lastOrder = Db::name('work_order')
            ->where('work_order_no', 'like', $prefix . $date . '%')
            ->order('id', 'desc')
            ->find();

        if ($lastOrder) {
            $lastNo = substr($lastOrder['work_order_no'], -6);
            $seq = str_pad($lastNo + 1, 6, '0', STR_PAD_LEFT);
        } else {
            $seq = '000001';
        }

        return $prefix . $date . $seq;
    }
}
